package com.example.keshe0337.biz;

import android.content.Context;

import com.example.keshe0337.dao.ParkingSpaceDao;
import com.example.keshe0337.database.AppDatabase;
import com.example.keshe0337.entity.ParkingSpace;

import java.util.ArrayList;
import java.util.List;

public class SpaceService {
    private final ParkingSpaceDao spaceDao;
    public SpaceService(Context context) {
        AppDatabase db = AppDatabase.getInstance(context);
        this.spaceDao = db.parkingSpaceDao();
    }

    public int addParkingSpace (ParkingSpace parkingSpace) {
        if (parkingSpace.getSpaceNum() == null || parkingSpace.getSpaceNum().isBlank()) {
            return 1;//停车位号为空
        }
        if (spaceDao.getPSByNum(parkingSpace.getSpaceNum()) != null) {
            return 2;//该停车号已存在
        }
        if (parkingSpace.getLocation() == null || parkingSpace.getLocation().isBlank()) {
            parkingSpace.setLocation("无介绍信息");
        }
        if (parkingSpace.getHourlyFee() == null) {
            parkingSpace.setHourlyFee(0.0);
        }
        parkingSpace.setStatus(true);
        spaceDao.insertPS(parkingSpace);
        return 0;
    }

    public int updateParkingSpace (ParkingSpace parkingSpace) {
        if (parkingSpace.getSpaceNum() == null || parkingSpace.getSpaceNum().isBlank()) {
            return 1;//停车位号为空
        }
        ParkingSpace psByNum = spaceDao.getPSByNum(parkingSpace.getSpaceNum());
        if (psByNum != null && !psByNum.getSpaceNum().equals(parkingSpace.getSpaceNum())) {
            return 2;//该停车号已存在
        }
        if (parkingSpace.getLocation() == null || parkingSpace.getLocation().isBlank()) {
            parkingSpace.setLocation("无介绍信息");
        }
        if (parkingSpace.getHourlyFee() == null) {
            parkingSpace.setHourlyFee(0.0);
        }
        parkingSpace.setStatus(true);
        spaceDao.updatePS(parkingSpace);
        return 0;
    }



    public int deleteParkingSpace(Long sId) {
        ParkingSpace parkingSpace = spaceDao.getPSById(sId);
        if (parkingSpace == null) {
            return 0;
        }
        spaceDao.deletePS(parkingSpace);
        return 0;
    }

    public List<ParkingSpace> getAllPSs() {
        return spaceDao.getAllPSs();
    }

    public List<ParkingSpace> getPSBySearch(String search) {
        List<ParkingSpace> parkingSpaces = spaceDao.getPSByTypeLike(search);
        if (parkingSpaces == null) {
            parkingSpaces = new ArrayList<>();
        }

        List<ParkingSpace> p = spaceDao.getPSByNumList(search);
        if (p == null) {
            p = new ArrayList<>();
        }
        parkingSpaces.addAll(p);
        return parkingSpaces;
    }

}
